<template>
  <div class="quotation-list">
    <!-- 添加查询条件 -->
    <view v-show="!previewVisible">
      <a-card :bordered="false" class="header-search-card card-wrapper" bodyStyle="padding: 0.3vw 1.2vw 0.2vw;">
        <a-form
          :model="searchParams"
          layout="inline"
          class="search-form"
        >
          <div class="search-container">
            <div class="search-fields">
              <div class="search-item">
                <label class="search-label">单号:</label>
                <div class="search-input">
                  <a-input
                    v-model:value="searchParams.xmqducdocno"
                    placeholder=""
                    allow-clear
                    size="small"
                  />
                </div>
              </div>

              <!-- <div class="search-item">
                <label class="search-label">版本:</label>
                <div class="search-input">
                  <a-input
                    v-model:value="searchParams.xmqduc001"
                    placeholder=""
                    allow-clear
                    size="small"
                  />
                </div>
              </div> -->

              <div class="search-item">
                <label class="search-label">客户编号:</label>
                <div class="search-input">
                  <a-input
                    v-model:value="searchParams.xmqduc007"
                    placeholder=""
                    allow-clear
                    size="small"
                  />
                </div>
              </div>

              <!-- <div class="search-item">
                <label class="search-label">创建日期:</label>
                <div class="search-input">
                  <a-date-picker
                    v-model:value="searchParams.xmqduccrtdt"
                    placeholder=""
                    style="width: 100%"
                    size="small"
                  />
                </div>
              </div> -->

              <div class="search-item">
                <label class="search-label">模板查询:</label>
                <div class="search-input">
                  <a-select
                    v-model:value="searchParams.templateCode"
                    placeholder=""
                    :options="dropdownOptions.templateOptions"
                    allow-clear
                    style="width: 100%"
                    size="small"
                  />
                </div>
              </div>

              <div>
              </div>

              <!-- <div class="search-item">
                <label class="search-label">状态:</label>
                <div class="search-input">
                  <a-select
                    v-model:value="searchParams.xmqducstus"
                    placeholder=""
                    :options="dropdownOptions.quoteCheckOptions"
                    allow-clear
                    style="width: 100%"
                    size="small"
                  />
                </div>
              </div> -->
            </div>

            <div class="search-item search-buttons-inline">
              <a-button type="primary" @click="handleSearch" size="small">
                <template #icon>
                  <SearchOutlined />
                </template>
                查询
              </a-button>
              <a-button type="primary" @click="handleReset" size="small">
                <template #icon>
                  <RedoOutlined />
                </template>
                重置
              </a-button>

              <a-button
                type="primary"
                @click="previewSelected"
                :loading="previewLoading"
                size="small"
              >
                <template #icon>
                  <EyeOutlined />
                </template>
                预览
              </a-button>

              <a-button
                type="primary"
                @click="exportSelected"
                :loading="exportLoading"
                size="small"
              >
                <template #icon>
                  <DownloadOutlined />
                </template>
                导出
              </a-button>

              <a-button
                type="primary"
                @click="handleEdit"
                size="small"
              >
                <template #icon>
                  <EditOutlined />
                </template>
                编辑
              </a-button>

              <a-button
                type="primary"
                @click="handleSubmitForReview"
                size="small"
              >
                <template #icon>
                  <CheckCircleOutlined />
                </template>
                审核
              </a-button>

              <a-button
                type="primary"
                @click="handleVersionUpgrade"
                size="small"
              >
                <template #icon>
                  <SwapOutlined />
                </template>
                版本升级
              </a-button>
            </div>
          </div>
        </a-form>
      </a-card>
    </view>

    <a-card title="" :bordered="false" class="card-wrapper" headStyle="min-height: 2.08vw;" bodyStyle="padding: 0.8vw 1.25vw;">
      <div class="table-container">
        <SortableTable
          :data="paginatedDataWithStatusText"
          :columns="columns"
          :header-hover-color="headerHoverColor"
          :show-sort-indicators="true"
          :sorted-indicator-color="'#000'"
          :unsorted-indicator-color="'rgba(0, 0, 0, 0.5)'"
          :header-style="headerStyle"
          @sort-change="handleSortChange"
          :sticky-header="true"
          :fixed-action="true"
          :get-row-class="getRowClass"
          @row-dblclick="handleRowDblClick"
          :resizable="true"
        >
          <template #column-index="{ index }">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>

          <template #column-selection="{ item }">
            <a-checkbox
              :checked="selectedRows.some(row => row.quoteCutUuid === item.quoteCutUuid)"
              @change="(e) => handleRowSelection(e, item)"
              @click.stop
            />
          </template>

          <template #header-selection>
            <a-checkbox
              :checked="isAllSelected"
              :indeterminate="isIndeterminate"
              @change="handleSelectAll"
            />
          </template>

          <template #column-actions="{ item }">
            <div class="action-cell">
              <a-button type="link" @click="showDrawer(item)">查看</a-button>
            </div>
          </template>
        </SortableTable>

        <!-- 无数据提示 -->
        <div v-if="paginatedData.length === 0" class="no-data">
          暂无数据
        </div>
      </div>

      <div class="pagination-wrapper">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :show-size-changer="true"
          :page-size-options="pagination.pageSizeOptions"
          @change="handlePageChange"
          @show-size-change="handlePageSizeChange"
        />
      </div>
    </a-card>

    <!-- Excel在线预览组件 -->
    <ExcelPreview
      v-model:visible="previewVisible"
      :file-url="previewFileUrl"
      :file-name="previewFileName"
      @close="closePreview"
      @retry="previewSelected"
    />

    <QuotationDetailDrawer
      :visible="open"
      :quotation-data="currentQuotation"
      @close="open = false"
      @update:visible="open = $event"
    />

    <!-- 审核弹窗 -->
    <a-modal
      v-model:open="reviewModalVisible"
      title="审核操作"
      :footer="null"
      :maskClosable="false"
      width="25vw"
      class="review-modal"
    >
      <div class="review-modal-content">

        <div class="review-buttons">
          <a-button
            type="primary"
            @click="confirmReview(2)"
            class="review-btn pass-btn"
          >
            <CheckOutlined />
            审核通过
          </a-button>
          <a-button
            type="primary"
            @click="confirmReview(3)"
            class="review-btn reject-btn"
          >
            <CloseOutlined />
            审核不通过
          </a-button>

        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick, watch, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import { SortableTable } from '@/components/custom';
import {
  qecutListApi, // 模切报价单列表接口
  getDitcApi, //获取模切报价单详情的下拉列表数据
  qecutExportsApi, // 模切报价单批量导出接口
  qecutQueryListApi, // 模切报价单编辑查询列表接口
  qecutExportNewApi, // 模切报价单编辑导出接口
  dieCuttingListSubmit, // 编辑列表提交审核接口
  dieCuttingUpgradeSubmit, // 编辑版本升级接口
} from '@/service/api/modules/die-cutting/die-cutting';
import { getDicts } from '@/service/api/dict'; // 添加字典接口
import { useRouterPush } from '@/hooks/common/router';
import QuotationDetailDrawer from './modules/quotation-detail-drawer.vue';
import ExcelPreview from '@/components/custom/excel-preview.vue';
import { message, Modal } from 'ant-design-vue';
import {
  SearchOutlined,
  RedoOutlined,
  EyeOutlined,
  EditOutlined,
  DownloadOutlined,
  CheckCircleOutlined,
  SwapOutlined
} from '@ant-design/icons-vue';
import { useTabStore } from '@/store/modules/tab'; // 添加这一行导入

// 添加表头样式响应式变量
const headerStyle = ref({ color: '#fff' }); //表头字体颜色
const headerHoverColor = ref(''); // 添加表头悬停背景色变量

// 添加状态映射
const stateMap = {
  0: '已创建',
  1: '待审核',
  2: '审核通过',
  3: '审核不通过'
};

const router = useRouter();
const { routerPushByKey } = useRouterPush();
const tabStore = useTabStore(); // 添加这一行获取tabStore实例

// 添加审核弹窗可见性控制
const reviewModalVisible = ref(false);
// 添加当前正在审核的记录
const currentReviewRecord = ref<any>(null);

// 添加下拉选项数据
const dropdownOptions = reactive({
  quoteCheckOptions: [],
  templateOptions: [] // 添加模板选项
});

// 模板字典映射
const stateMaping: any = ref([]);

// 控制行是否可点击
const enableRowClick = ref(true);

// 查询参数
const searchParams = reactive({
  xmqducdocno: null,  // 单号
  xmqduc001: null,    // 版本
  xmqduc007: null,    // 产品编码
  xmqduccrtdt: null,  // 资料创建日
  xmqducstus: null,   // 状态
  templateCode: null  // 模板编码
});

// 选中的行
const selectedRows = ref<any[]>([]);

// 计算是否全选
const isAllSelected = computed(() => {
  return paginatedDataWithStatusText.value.length > 0 &&
         selectedRows.value.length === paginatedDataWithStatusText.value.length;
});

// 计算是否部分选中
const isIndeterminate = computed(() => {
  return selectedRows.value.length > 0 &&
         selectedRows.value.length < paginatedDataWithStatusText.value.length;
});

// 表格列定义
const columns = [
  {
    key: 'selection',
    label: '', // 保持为空，使用自定义表头模板
    width: '3.125vw'
  },
  {
    key: 'index',
    label: '序号',
    width: '3.125vw'
  },
  {
    key: 'xmqduc007',
    label: '客户编号',
    width: '6.25vw'
  },
  {
    key: 'xmqduc002',
    label: '报价申请单号',
    width: '9vw'
  },
  {
    key: 'xmqduc003',
    label: '报价申请单版本',
    width: '8vw'
  },
  {
    key: 'insideVer',
    label: '内部版本号',
    width: '5vw'
  },
  {
    key: 'xmqduc007Name',
    label: '客户名称',
    width: '15vw'
  },
  {
    key: 'xmqducdocno',
    label: '单号',
    width: '9vw'
  },
  {
    key: 'xmqduc001',
    label: '版本',
    width: '3.125vw'
  },
  {
    key: 'templateCode',
    label: '模版名称',
    width: '5vw'
  },
  // {
  //   key: 'xmqducstusText',
  //   label: '状态',
  //   width: '4.17vw'
  // },
  {
    key: 'state',
    label: '状态',
    width: '4.17vw'
  },
  {
    key: 'stateText',
    label: '状态',
    width: '6vw'
  },
  // {
  //   key: 'xmqducstus',
  //   label: '状态码',
  //   width: '4.17vw'
  // },
  {
    key: 'xmqduc004',
    label: '产品编码',
    width: '8vw'
  },
  {
    key: 'xmqduc011Name',
    label: '报价人员',
    width: '5.21vw'
  },
  {
    key: 'xmqduc005',
    label: '品名',
    width: '10vw'
  },
  {
    key: 'xmqduc006',
    label: '规格',
    width: '10vw'
  },
  {
    key: 'xmqduc008',
    label: '客户货号',
    width: '8vw'
  },
  {
    key: 'xmqduc009',
    label: 'Model',
    width: '6vw'
  },
  {
    key: 'xmqduc010',
    label: '终端货号',
    width: '7vw'
  },
  // {
  //   key: 'xmqduc012',
  //   label: '报价部门',
  //   width: '5.21vw'
  // },
  // {
  //   key: 'xmqduc013',
  //   label: '报价币种',
  //   width: '5vw'
  // },
  // {
  //   key: 'xmqduc014',
  //   label: '税种',
  //   width: '4.17vw'
  // },
  // {
  //   key: 'xmqduc015',
  //   label: '报价数量',
  //   width: '5vw'
  // },
  {
    key: 'xmqduccrtdt',
    label: '资料创建日',
    width: '9vw'
  },
  {
    key: 'xmqducmoddt',
    label: '最近修改日',
    width: '9vw'
  },
  // {
  //   key: 'actions',
  //   label: '操作',
  //   width: '6.25vw',
  //   fixed: true
  // }
];

// 表格数据（写死的数据）
const tableData = ref([]);
// 状态码映射
const statusMap = ref({});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 100,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
});

const getDitc = () => {
  getDitcApi().then(res => {
    const data = res.data;
      // 处理quote_check数据，用于状态查询下下拉选项
      if (data.quote_check && Array.isArray(data.quote_check)) {
        dropdownOptions.quoteCheckOptions = data.quote_check.map(item => ({
          label: item.gzcbl004,
          value: item.gzcbl002
        }));
        console.log('quote_check:', dropdownOptions);
        // 构建状态码映射
        const statusMapping = {};
        data.quote_check.forEach(item => {
          statusMapping[item.gzcbl002] = item.gzcbl004;
        });
        statusMap.value = statusMapping;
        console.log('statusMap:', statusMap);
        // 更新搜索表单中的选项
        // initDropdownOptions();
      }
  });
};

// 获取模板字典数据
const getState = () => {
  getDicts('quote_temp_code').then( res => {
    const dict = res.otherData.data;
    stateMaping.value = dict;
    // 转换为下拉选项格式
    dropdownOptions.templateOptions = dict.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictValue
    }));

    // 如果有模板数据，默认选中第一个
    if (dict.length > 0 && !searchParams.templateCode) {
      searchParams.templateCode = dict[0].dictValue;
    }
    // 在设置完模板选项和默认值后，立即查询数据
    qecut();
  });
};

const qecut = () => {
  // 使用动态分页参数
  const params = {
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    ...searchParams
  };

  // 确保模板编码参数传递
  if (searchParams.templateCode) {
    params.templateCode = searchParams.templateCode;
  }

  // 修复日期参数格式问题
  if (params.xmqduccrtdt && typeof params.xmqduccrtdt === 'object' && params.xmqduccrtdt.$d) {
    // 如果是 dayjs 对象，转换为标准日期字符串格式
    params.xmqduccrtdt = dayjs(params.xmqduccrtdt.$d).format('YYYY-MM-DD');
  } else if (params.xmqduccrtdt === null || params.xmqduccrtdt === undefined || params.xmqduccrtdt === '') {
    // 如果日期为空，确保传递 null 值
    params.xmqduccrtdt = null;
  }

  // console.log('查询参数:', params)

  qecutQueryListApi(params).then(res => {
    const data = res.otherData;
    if (data.code === 200) {
      // 保存当前选中行的quoteCutUuid
      const selectedUuids = selectedRows.value.map(row => row.quoteCutUuid);
      // console.log('当前选中的UUID:', selectedUuids);

      tableData.value = data.rows;
      // 使用响应式赋值更新 total（已 reactive，直接赋值即为"setter"行为）
      pagination.total = data.total;

      // 根据之前保存的quoteCutUuid恢复选中状态
      nextTick(() => {
        // console.log('表格数据更新后的新数据:', data.rows);
        const newSelectedRows = data.rows.filter(row =>
          selectedUuids.includes(row.quoteCutUuid)
        );
        selectedRows.value = newSelectedRows;
      });
    }
    console.log('接口返回数据:', data);
  });
}

// 修复：直接使用后端返回的数据，不再进行前端分页
const paginatedData = computed(() => {
  return tableData.value;
});

// 自定义行类名函数，用于添加行点击样式
const getRowClass = (index) => {
  const baseClass = index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
  // 如果启用行点击功能，添加可点击样式
  return enableRowClick.value ? `${baseClass} clickable-row` : baseClass;
};

// 处理排序变化
const handleSortChange = (sortState) => {
  console.log('排序状态:', sortState);
  // 在这里可以处理排序逻辑
};

// 处理分页变化
const handlePageChange = (page, pageSize) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  // 分页变化时重新查询数据
  qecut();
};

// 处理页面大小变化
const handlePageSizeChange = (current, size) => {
  pagination.current = current;
  pagination.pageSize = size;
  // 页面大小变化时重新查询数据
  qecut();
};

// 跳转到详情页面 - 使用带参数的路由跳转
const goToDetail = (record) => {
  console.log('跳转到详情页面:', record);
  // 使用 routerPushByKey 方法跳转到报价明细页面，传递参数
  routerPushByKey('die-cutting-quotation_maintenance-management_quotation-edit-details', {
    query: {
      xmqeucdocno: record.xmqducdocno,
      xmqeuc001: record.xmqduc001,
      xmqeucent: record.xmqducent,
      tabTitle: record.xmqduc007, // 添加自定义标签页标题
      quoteCutUuid: record.quoteCutUuid,
      templateCode: searchParams.templateCode, // 添加模板代码
      type: 'bjcx'
    },
  });
};

// 带状态文本的分页数据
const paginatedDataWithStatusText = computed(() => {
  return tableData.value.map((item, index) => {
    return {
      ...item,
      index: index // 为每行数据添加索引
    };
  }).map(item => {
    // 查找模板名称
    const template = stateMaping.value.find((t: any) => t.dictValue === item.templateCode);
    return {
      ...item,
      xmqducstusText: statusMap.value[item.xmqducstus] || item.xmqducstus,
      templateCode: template ? template.dictLabel : item.templateCode,
      stateText: stateMap[item.state] || item.state  // 添加状态中文映射
    };
  });
});

// 处理行双击事件
const handleRowDblClick = (item, index) => {
  console.log('双击行数据:', item);
  // 可以在这里添加行双击后的处理逻辑，例如跳转到详情页
  goToDetail(item);
};

// 查询方法
const handleSearch = () => {
  pagination.current = 1;
  qecut();
  // 查询后清空已选中的行
  selectedRows.value = [];
};

// 重置方法
const handleReset = () => {
  nextTick(() => {
    searchParams.xmqducdocno = null;
    searchParams.xmqduc001 = null;
    searchParams.xmqduc007 = null;
    searchParams.xmqduccrtdt = null;
    searchParams.xmqducstus = null;
    handleSearch();
  });
};

// 处理行选择
const handleRowSelection = (e, record) => {
  const checked = e.target.checked;
  if (checked) {
    // 添加到选中项
    selectedRows.value.push(record);
  } else {
    // 从选中项中移除
    const index = selectedRows.value.findIndex(
      item => item.quoteCutUuid === record.quoteCutUuid
    );
    if (index > -1) {
      selectedRows.value.splice(index, 1);
    }
  }
  console.log('已选行:', selectedRows.value);
};

// 全选/取消全选
const handleSelectAll = (e) => {
  const checked = e.target.checked;

  if (checked) {
    // 全选
    selectedRows.value = [...paginatedDataWithStatusText.value];
  } else {
    // 取消全选
    selectedRows.value = [];
  }
};

const open = ref<boolean>(false);
const currentQuotation = ref({}); // 用于存储当前查看的报价单数据

// 预览相关状态
const previewLoading = ref(false);
const previewVisible = ref(false);
const previewFileUrl = ref('');
const previewFileName = ref('');

const afterOpenChange = (bool: boolean) => {
  console.log('open', bool);
};

const showDrawer = (record) => {
  console.log('显示抽屉，记录数据:', record);
  // 确保传递必要的参数
  currentQuotation.value = {
    xmqducent: record.xmqducent,
    xmqducdocno: record.xmqducdocno,
    xmqduc001: record.xmqduc001
  };
  open.value = true;
};

// 在线预览选中项
const previewSelected = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择要预览的报价单');
    return;
  }

  // if (selectedRows.value.length > 1) {
  //   message.warning('只能选择一条数据进行预览');
  //   return;
  // }

  // 构造导出数据格式
  const exportData = {
    templateCode: searchParams.templateCode,
    quoteCut: selectedRows.value.map(item => ({
      xmqducent: item.xmqducent,
      xmqducdocno: item.xmqducdocno,
      xmqduc001: item.xmqduc001,
      quoteCutUuid: item.quoteCutUuid,
    }))
  };
  // const exportData = {
  //   xmqducent: selectedRows.value[0].xmqducent,
  //   xmqducdocno: selectedRows.value[0].xmqducdocno,
  //   xmqduc001: selectedRows.value[0].xmqduc001
  // };
  console.log('在线预览选中项2222:', exportData)
  previewLoading.value = true;

  qecutExportsApi(exportData)
    .then((res: any) => {
      // 检查接口返回的类型是否为Excel文件
      if (res.data.type == 'application/json') {
        // 如果是JSON格式，说明导出失败
        const errorMsg = res.otherData?.message || '获取预览文件失败';
        message.error(errorMsg);
        console.error('预览失败:', errorMsg);
        return;
      }

      // 创建Blob对象
      const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });

      // 创建临时URL
      const fileURL = URL.createObjectURL(blob);
      const fileName = `报价明细_${new Date().getTime()}.xlsx`;

      // 设置预览参数
      previewFileUrl.value = fileURL;
      previewFileName.value = fileName;
      previewVisible.value = true;
    })
    .catch((error: any) => {
      const errorMsg = '预览失败: ' + (error.message || '获取预览文件失败');
      message.error(errorMsg);
      console.error('预览失败:', error);
    })
    .finally(() => {
      previewLoading.value = false;
    });
};

// 关闭预览
const closePreview = () => {
  previewVisible.value = false;
  // 清理URL对象以释放内存
  if (previewFileUrl.value) {
    URL.revokeObjectURL(previewFileUrl.value);
    previewFileUrl.value = '';
  }
};

const exportLoading = ref(false);
// 导出选中项
const exportSelected = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择要导出的报价单');
    return;
  }

  // if (selectedRows.value.length > 1) {
  //   message.warning('只能选择一条数据进行导出');
  //   return;
  // }

  // 构造导出数据格式
  const exportData = {
    templateCode: searchParams.templateCode,
    quoteCut: selectedRows.value.map(item => ({
      xmqducent: item.xmqducent,
      xmqducdocno: item.xmqducdocno,
      xmqduc001: item.xmqduc001,
      quoteCutUuid: item.quoteCutUuid,
    }))
  };
  // const exportData = {
  //   xmqducent: selectedRows.value[0].xmqducent,
  //   xmqducdocno: selectedRows.value[0].xmqducdocno,
  //   xmqduc001: selectedRows.value[0].xmqduc001
  // };
  exportLoading.value = true;
  console.log('导出数据:', exportData);
  qecutExportsApi(exportData).then((res: any) => {
    // 创建下载链接
    const blob = new Blob([res.data]);
    const fileName = `报价编辑明细.xlsx`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
  })
  .catch((error: any) => {
    console.error('导出失败:', error);
  })
  .finally(() => {
    exportLoading.value = false;
  });
};

// 添加编辑和编辑查询处理函数
const handleEdit = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择一条数据进行编辑');
    return;
  }

  if (selectedRows.value.length > 1) {
    message.warning('只能选择一条数据进行编辑');
    return;
  }

  const record = selectedRows.value[0];
  // 跳转到报价单编辑页面
  routerPushByKey('die-cutting-quotation_maintenance-management_quotation-edit', {
    query: {
      xmqeucdocno: record.xmqducdocno,
      xmqeuc001: record.xmqduc001,
      xmqeucent: record.xmqducent,
      tabTitle: record.xmqduc007, // 添加自定义标签页标题
      quoteCutUuid: record.quoteCutUuid,
      templateCode: searchParams.templateCode, // 添加模板代码
      type: 'bjcx'
    },
  });
};

const handleEditInquiry = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择一条数据进行编辑查询');
    return;
  }

  if (selectedRows.value.length > 1) {
    message.warning('只能选择一条数据进行编辑查询');
    return;
  }

  const record = selectedRows.value[0];
  // 跳转到报价单编辑查询页面
  routerPushByKey('die-cutting-quotation_maintenance-management_quotation-edit-inquiry', {
    query: {
      xmqeucdocno: record.xmqducdocno,
      xmqeuc001: record.xmqduc001,
      xmqeucent: record.xmqducent,
      tabTitle: record.xmqduc007 // 添加自定义标签页标题
    },
  });
};

// 添加提交审核处理函数
const handleSubmitForReview = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择一条数据进行提交审核');
    return;
  }

  if (selectedRows.value.length > 1) {
    message.warning('只能选择一条数据进行提交审核');
    return;
  }

  const record: any = selectedRows.value[0];

  // 只有当state等于1的时候才能点击审核按钮
  if (record.state !== 1) {
    message.warning('只有状态为待审核的记录才能进行审核操作');
    return;
  }

  // 设置当前审核记录并显示审核弹窗
  currentReviewRecord.value = record;
  reviewModalVisible.value = true;
};

// 确认审核操作
const confirmReview = (state: any) => {
  const record: any = currentReviewRecord.value;

  if (!record) {
    message.warning('审核记录不存在');
    return;
  }

  dieCuttingListSubmit({
    mqeucdocno: record.xmqducdocno,
    xmqeuc001: record.xmqduc001,
    xmqeucent: record.xmqducent,
    tabTitle: record.xmqduc007, // 添加自定义标签页标题
    templateCode: searchParams.templateCode, // 添加模板代码
    quoteCutUuid: Number(record.quoteCutUuid),
    state: state // 审核状态: 2-审核不通过, 3-审核通过
  }).then( res => {
    console.log(res, 2222222222)
    const data = res.otherData
    if( data.code === 200){
      message.success(res.otherData?.message || '提交审核成功');
      // 关闭弹窗
      reviewModalVisible.value = false;
      // 重新加载数据
      qecut();
    }
  })
};

// 取消审核操作
const cancelReview = () => {
  reviewModalVisible.value = false;
  currentReviewRecord.value = null;
};

// 添加版本升级处理函数
const handleVersionUpgrade = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择一条数据进行版本升级');
    return;
  }

  if (selectedRows.value.length > 1) {
    message.warning('只能选择一条数据进行版本升级');
    return;
  }

  const record = selectedRows.value[0];

  Modal.confirm({
    title: '确认版本升级',
    content: `确定要对单号为 ${record.xmqducdocno} 的报价单进行版本升级吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      console.log('版本升级:', record);
      dieCuttingUpgradeSubmit({
        xmqeucdocno: record.xmqducdocno,
        xmqeuc001: record.xmqduc001,
        xmqeucent: record.xmqducent,
        tabTitle: record.xmqduc007, // 添加自定义标签页标题
        quoteCutUuid: Number(record.quoteCutUuid),
        templateCode: searchParams.templateCode, // 添加模板代码
      }).then((res) => {
        console.log(res,1111111)

        const data = res.otherData
        if( data.code === 200){
          // 跳转到报价单编辑页面
          routerPushByKey('die-cutting-quotation_maintenance-management_quotation-edit', {
            query: {
              xmqeucdocno: record.xmqducdocno,
              xmqeuc001: record.xmqduc001,
              xmqeucent: record.xmqducent,
              tabTitle: record.xmqduc007, // 添加自定义标签页标题
              quoteCutUuid: Number(record.quoteCutUuid),
              templateCode: searchParams.templateCode, // 添加模板代码
              type: 'bjcx'
            },
          });
        }
      })
    },
    onCancel() {
      console.log('取消版本升级');
    },
  });
};


const route = useRoute();

// 监听路由变化，确保每次进入页面都重新请求数据
watch(
  () => route.fullPath,
  (newPath, oldPath) => {
    console.log('路由路径变化:', newPath, oldPath);
    // 检查是否进入了当前页面
    if (newPath.includes('/die-cutting-quotation/maintenance-management/quotation-edit-inquiry')) {
      // 每次进入页面都重新请求数据
      qecut();
    }
  },
  { immediate: true }
);

// 添加标签页关闭监听
let currentTabId = null;
onMounted(() => {
  // 获取当前标签页ID
  currentTabId = tabStore.getTabIdByRoute(route);
  console.log('当前标签页ID:', currentTabId);

  // 监听标签页切换事件，判断是否需要清空选中行
  const unwatch = watch(
    () => tabStore.tabs,
    (newTabs, oldTabs) => {
      // 检查当前标签页是否被关闭
      console.log('标签页切换事件:', newTabs, oldTabs);
      const isCurrentTabClosed = oldTabs.some(tab => tab.id === currentTabId)
        && !newTabs.some(tab => tab.id === currentTabId);

      if (isCurrentTabClosed) {
        // 当前标签页已被关闭，清空选中行
        console.log('标签页已关闭，清空选中行');
        selectedRows.value = [];
      }
    },
    {
      deep: true,
      flush: 'post'
    }
  );

  // 在组件卸载时取消监听
  onBeforeUnmount(() => {
    unwatch();
  });
});

onMounted(() => {
  getState(); // 获取模板字典数据
  getDitc();
  // 已移除延迟执行的qecut调用，现在由getState方法内部在适当时机触发
});
</script>

<style scoped>
:deep(.card-wrapper){
  border-radius: 4px;
}

.quotation-list {
  background-color: #f3f3f3;
  padding: 0.2vw 0.4vw;
  border-radius: 0.21vw;
  height: calc(100vh - 5.5vw);
  display: flex;
  flex-direction: column;
}

:deep(.ant-card) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.ant-card-body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.pagination-wrapper {
  margin-top: 0.52vw;
  display: flex;
  justify-content: flex-end;
}

.action-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.no-data {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #999;
  font-size: 0.73vw;
}

/* 可点击行的样式 */
.clickable-row {
  cursor: pointer;
}

.clickable-row:hover {
  background-color: #e6f7ff !important;
}

.search-container {
  display: flex;
  width: 100%;
  align-items: flex-end; /* 修改为flex-end，使内容底部对齐 */
  gap: 0.5vw;
  flex-wrap: wrap; /* 允许换行 */
}

.search-fields {
  display: flex;
  flex: 1;
  gap: 0.5vw;
  flex-wrap: wrap;
}

.search-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  min-width: 12vw;
}

.search-label {
  font-size: 0.8vw;
  margin-bottom: 0;
  margin-right: 0.2vw;
  color: #000000;
  white-space: nowrap;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  min-width: 0;
}

.search-buttons-inline {
  display: flex;
  gap: 0.3vw;
  align-items: center;
  margin-left: auto;
  white-space: nowrap;
}

:deep(.ant-input) {
  font-size: 0.8vw !important;
  height: 1.8vw;
}

:deep(.ant-input input) {
  font-size: 0.8vw !important;
}

:deep(.ant-input::placeholder) {
  font-size: 0.8vw !important;
}

:deep(.ant-select) {
  font-size: 0.8vw !important;
}

:deep(.ant-select-selector) {
  height: 1.8vw !important;
  align-items: center !important;
}

:deep(.ant-select-selection-item) {
  line-height: 1.6vw !important;
  align-items: center !important;
  font-size: 0.8vw;
}

:deep(.ant-select-dropdown) {
  font-size: 0.8vw;
}

:deep(.ant-select-item) {
  font-size: 0.8vw;
  min-height: 1.8vw;
}

:deep(.ant-picker) {
  font-size: 0.8vw;
  height: 1.8vw;
  padding: 0 0.6vw;
  display: flex;
  align-items: center;
}

:deep(.ant-picker-input > input) {
  height: 1.8vw;
}

:deep(.ant-btn) {
  font-size: 0.8vw;
  height: 1.8vw;
  padding: 0 0.5vw;
  border-radius: 0.2vw;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: none;
}

/* 修改查询按钮和导出、编辑按钮选中后的背景色为#5F9EA0 */
:deep(.ant-btn-primary) {
  background-color: #5F9EA0;
  border-color: #5F9EA0;
  box-shadow: none;
}

.header-search-card {
  margin-bottom: 0.5vw;
}

/* 响应式处理 */
@media (max-width: 1200px) {
  .search-container {
    flex-direction: row;
    align-items: flex-end;
    gap: 0.5vw;
  }

  .search-fields {
    flex: 1;
    min-width: 0;
  }

  .search-item {
    min-width: 12vw;
  }

  .search-buttons-inline {
    margin-left: 0.5vw;
  }
}

@media (max-width: 768px) {
  .search-container {
    flex-wrap: wrap;
  }

  .search-fields {
    flex: auto;
    width: 100%;
  }

  .search-item {
    min-width: calc(50% - 0.25vw);
  }

  .search-buttons-inline {
    width: 100%;
    margin-left: 0;
    margin-top: 0.5vw;
  }
}

.review-modal-content {
  padding: 2vw 1vw;
  text-align: center;
}

.review-tip {
  font-size: 1vw;
  margin-bottom: 2vw;
  color: #666;
}

.review-buttons {
  display: flex;
  justify-content: center;
  gap: 1vw;
}

.review-btn {
  font-size: 0.8vw !important;
  height: 2vw !important;
  padding: 0 1.2vw !important;
  border-radius: 0.3vw !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

.pass-btn {
  background-color: #6ACBB7 !important;
  border-color: #6ACBB7 !important;
}

.reject-btn {
  background-color: #F75F79 !important;
  border-color: #F75F79 !important;
}

.cancel-btn {
  background-color: #ffffff !important;
  border-color: #d9d9d9 !important;
  color: #333333 !important;
}

.review-modal :deep(.ant-modal-content) {
  border-radius: 0.5vw;
}

.review-modal :deep(.ant-modal-header) {
  border-radius: 0.5vw 0.5vw 0 0;
  background-color: #f0f2f5;
  padding: 1vw 1.5vw;
  border-bottom: 1px solid #e8e8e8;
}

.review-modal :deep(.ant-modal-title) {
  font-size: 1.1vw;
  font-weight: 500;
  color: #333;
}

.review-header {
  margin-bottom: 1.5vw;
}

.review-icon {
  font-size: 2vw;
  color: #1890ff;
  margin-bottom: 0.5vw;
}

.review-title {
  font-size: 1.2vw;
  font-weight: 600;
  color: #333;
  margin: 0;
}
</style>
